<?php

namespace app\admin\logic;

use app\admin\validate\WorkStation as WorkStationValidate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

class WorkStationLogic extends BaseLogic
{
    /**
     * 获取工位查询条件
     * @param $branchid
     * @param $floorid
     * @param $regionid
     * @param $wsid
     * @return array
     */
    public function get_search_ws_maps($branchid, $floorid, $regionid, $wsid)
    {
        $maps = [];
        if ($branchid != -1) {
            $f_maps = [];
            $f_maps[] = ['branchid', '=', $branchid];
            $floorids = model('floor')->get_column($f_maps, 'id');

            $m_maps = [];
            $m_maps[] = ['floorid', 'in', $floorids];
            $regionids = model('region')->get_column($m_maps, 'id');
            $maps[] = ['regionid', 'in', $regionids];
        }
        if ($floorid != -1) {
            $m_maps = [];
            $m_maps[] = ['floorid', '=', $floorid];
            $regionids = model('region')->get_column($m_maps, 'id');
            $maps[] = ['regionid', 'in', $regionids];
        }
        if ($regionid != -1) {
            $maps[] = ['regionid', '=', $regionid];
        }
        if ($wsid != -1) {
            $maps[] = ['id', '=', $wsid];
        }
        return $maps;
    }

    /**
     * 获取工位
     * @param $params
     * @return mixed
     */
    public function get_ws($params)
    {
        $now_date = date('Y-m-d');

        $cvr = new \app\common\controller\CountVisitorRecord();

        $maps = $this->get_search_ws_maps($params['branchid'], $params['floorid'], $params['regionid'], $params['wsid']);
        $limit = ($params['page'] - 1) * $params['rows'];

        $list = model('work_station')->get_list($maps, 'id,regionid,number,work_type,price,company_name,company_out_time,wechat_mini_code_pic', 'id desc', '', $limit, $params['rows']);
        foreach ($list as $k => $v) {
            $list[$k]['work_type_zw'] = $v->work_type_name;
            $list[$k]['price'] = deal_number_div_100($v['price']);

            //查找区域
            $r_maps = [];
            $r_maps[] = ['id', '=', $v['regionid']];
            $r_detail = model('region')->get_detail($r_maps, 'id,floorid,name');
            $list[$k]['region_zw'] = $r_detail['name'];

            //查找楼层
            $f_maps = [];
            $f_maps[] = ['id', '=', $r_detail['floorid']];
            $f_detail = model('floor')->get_detail($f_maps, 'id,branchid,name');
            $list[$k]['floorid'] = $f_detail['id'];
            $list[$k]['floor_zw'] = $f_detail['name'];

            //查找分部
            $b_maps = [];
            $b_maps[] = ['id', '=', $f_detail['branchid']];
            $b_detail = model('branch')->get_detail($b_maps, 'id,name');
            $list[$k]['branchid'] = $b_detail['id'];
            $list[$k]['branch_zw'] = $b_detail['name'];

            //获取工位访问数量
            $r = $cvr->count_ws_vr_num($v['id']);
            $list[$k]['wss_num'] = $r['num'];
        }

        $total_num = model('work_station')->get_count($maps, 'id');

        $data['list'] = $list;
        $data['total_num'] = $total_num;
        return $this->get_response(1, 'OK', $data);
    }

    /**
     * 获取沟通备注查询条件
     * @param $wsid
     * @return array
     */
    public function get_search_remark_maps($wsid)
    {
        $maps = [];
        $maps[] = ['remark', '<>', ''];
        $maps[] = ['wsid', '=', $wsid];

        return $maps;
    }

    /**
     * 检查新增工位规则
     * @param $params
     * @return mixed
     */
    public function check_add_ws_rule($params)
    {
        $validate = new WorkStationValidate();
        $r = $validate->scene('add')->check($params);
        if (!$r) {
            return $this->get_response(0, $validate->getError());
        }

        $maps = [];
        $maps[] = ['regionid', '=', $params['regionid']];
        $maps[] = ['number', '=', trim($params['number'])];
        $ws_detail = model('work_station')->get_detail($maps, 'id');
        if (!empty($ws_detail)) {
            return $this->get_response(0, '该工位已存在');
        }
        return $this->get_response(1, 'OK');
    }

    /**
     * 检查修改工位规则
     * @param $params
     * @return mixed
     */
    public function check_save_ws_rule($params)
    {
        $validate = new WorkStationValidate();
        $r = $validate->scene('edit_ws')->check($params);
        if (!$r) {
            return $this->get_response(0, $validate->getError());
        }

        $maps = [];
        $maps[] = ['id', '=', $params['wsid']];
        $ws_detail = model('work_station')->get_detail($maps, 'id');
        if (empty($ws_detail)) {
            return $this->get_response(0, '该工位不存在');
        }

        $maps = [];
        $maps[] = ['id', '<>', $params['wsid']];
        $maps[] = ['number', '=', trim($params['number'])];
        $detail = model('work_station')->get_detail($maps, 'id');
        if (!empty($detail)) {
            //return $this->get_response(0,'该工位已存在');
        }

        $data['ws_detail'] = $ws_detail;
        return $this->get_response(1, 'OK', $data);
    }

    /**
     * 检查修改公司规则
     * @param $params
     * @return mixed
     */
    public function check_save_company_rule($params)
    {
        $validate = new WorkStationValidate();
        $r = $validate->scene('edit_company')->check($params);
        if (!$r) {
            return $this->get_response(0, $validate->getError());
        }

        $maps = [];
        $maps[] = ['id', '=', $params['wsid']];
        $ws_detail = model('work_station')->get_detail($maps, 'id');
        if (empty($ws_detail)) {
            return $this->get_response(0, '该工位不存在');
        }

        $data['ws_detail'] = $ws_detail;
        return $this->get_response(1, 'OK', $data);
    }

    /**
     * 导入工位
     * @param $file
     * @return mixed
     */
    public function import_ws($file)
    {
        if (!empty($file)) {
            $info = $file->move(\think\facade\App::getRootPath() . 'public/uploads');
            $filename = 'uploads/' . $info->getSaveName();
        } else {
            return $this->get_response(0, '请上传文件');
        }
        if ($filename) {
            $pathinfo = pathinfo($filename);

            if ($pathinfo['extension'] != 'xlsx') {
                return $this->get_response(0, '文件为excel表格，且必须为xlsx格式');
            }

            $encode = 'utf-8';
            $objReader = IOFactory::createReader('Xlsx');
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($filename, $encode);
            $objWorksheet = $objPHPExcel->getActiveSheet(0); //获取第一个工作表
            $highestRow = $objWorksheet->getHighestRow(); //取得总行数
            $highestColumn = $objWorksheet->getHighestColumn(); //取得总列数
            $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
            $excelData = array();
            for ($row = 2; $row <= $highestRow; $row++) { //如果是第2行导入 需改$row = 2
                $excelRow = $row - 2;
                for ($col = 1; $col < $highestColumnIndex + 1; $col++) {
                    $excelData[$excelRow][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                }
            }
            //halt($excelData);
            $dataMysql = [];
            foreach ($excelData as $k => $v) {
                //查找分部
                $maps = [];
                $maps[] = ['name', '=', $v[0]];
                $b_detail = model('branch')->get_detail($maps, 'id');
                if (empty($b_detail)) {
                    continue;
                }

                //查找楼层
                $maps = [];
                $maps[] = ['branchid', '=', $b_detail['id']];
                $maps[] = ['name', '=', $v[1]];
                $f_detail = model('floor')->get_detail($maps, 'id');
                if (empty($f_detail)) {
                    continue;
                }

                //查找区域
                $maps = [];
                $maps[] = ['floorid', '=', $f_detail['id']];
                $maps[] = ['name', '=', $v[2]];
                $maps[] = ['is_cp_ws', '=', 1];
                $r_detail = model('region')->get_detail($maps, 'id');
                if (empty($r_detail)) {
                    continue;
                }

                //检查工位
                $maps = [];
                $maps[] = ['regionid', '=', $r_detail['id']];
                $maps[] = ['number', '=', $v['3']];
                $ws_detail = model('work_station')->get_detail($maps, 'id');
                if (!empty($ws_detail)) {
                    continue;
                }

                if (empty($v['3'])) {
                    continue;
                }

                $temp_data['regionid'] = $r_detail['id'];
                $temp_data['number'] = !empty(trim($v['3'])) ? trim($v['3']) : '';
                $temp_data['work_type'] = !empty(trim($v['4'])) ? trim($v['4']) : 1;
                $temp_data['measure'] = !empty(trim($v['5'])) ? trim($v['5']) : 0;
                $temp_data['price'] = !empty(trim($v['6'])) ? deal_number_mul_100(trim($v['6'])) : 0;
                $temp_data['suggest_person_num'] = !empty(trim($v['7'])) ? trim($v['7']) : 0;
                $temp_data['window_direction'] = !empty(trim($v['8'])) ? trim($v['8']) : '';
                $temp_data['is_indoor_air'] = !empty(trim($v['9'])) ? trim($v['9']) : 0;
                $temp_data['company_name'] = !empty(trim($v['10'])) ? trim($v['10']) : '';
                $temp_data['company_person'] = !empty(trim($v['11'])) ? trim($v['11']) : '';
                $temp_data['company_tel'] = !empty(trim($v['12'])) ? trim($v['12']) : '';
                if (empty(trim($v['13']))) {
                    $temp_data['company_out_time'] = '2019-11-01';
                } else {
                    if (strpos(trim($v['13']), '/') === 4) {
                        $temp_data['company_out_time'] = date('Y-m-d', strtotime(trim($v['13'])));
                    } else {
                        $temp_data['company_out_time'] = date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp(trim($v[13])));
                    }
                }
                if (empty(trim($v['14']))) {
                    $temp_data['company_out_time'] = '2019-11-01';
                } else {
                    if (strpos(trim($v['14']), '/') === 4) {
                        $temp_data['company_in_time'] = date('Y-m-d', strtotime(trim($v['14'])));
                    } else {
                        $temp_data['company_in_time'] = date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp(trim($v[14])));
                    }
                }

                $temp_data['company_introduce'] = !empty(trim($v['15'])) ? trim($v['15']) : '';
                $temp_data['company_business'] = !empty(trim($v['16'])) ? trim($v['16']) : '';
                $dataMysql[] = $temp_data;
            }
            $r = model('work_station')->insertAll($dataMysql);
            if ($r) {
                $data['total_num'] = count($excelData);
                $data['success_num'] = count($dataMysql);
                return $this->get_response(1, 'OK', $data);
            }
            return $this->get_response(0, '导入失败');
        }
    }
}
